package com.wehealth;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.umeng.analytics.MobclickAgent;
import com.wehealth.adapter.Adapter_QuestionList;
import com.wehealth.adapter.Adapter_QuestionReply;
import com.wehealth.adapter.Adapter_message;
import com.wehealth.adapter.QuestionReplyDate;
import com.wehealth.dm.DM_Messages;
import com.wehealth.dm.QuestionData;
import com.wehealth.dm.User;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

@SuppressLint("ValidFragment")
public class Question_reply_add extends Fragment {
	
	private static  String JSONResult;
	private List<QuestionReplyDate> listData;
	private MainActivity context;
    private  String QID;
    private ListView listView;
	private static final int NET_ERROR = -100;
	private static final int NOT_RECORD = -101;
	private static final int NOUSER_ERROR =-102;
	private ProgressBar mProgress;
	private QuestionData mData;
	private EditText  replyEt;
	private String  reply;
	private User user;

	public  Question_reply_add()
	{
		Log.i("init:", "Message"); 

	}
	
	public  void setQID(String qid)
	{
		QID = qid;
	}
	
	
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return  inflater.inflate(R.layout.question_reply_add, null);
	}
	
	
	
	public void onActivityCreated(Bundle savedInstanceState){
		
		super.onActivityCreated(savedInstanceState);
		
		//SIMMON_ADD
		//读取接口数据
	    context = (MainActivity)getActivity();
	    user = context.getUserInfo();
		MobclickAgent.openActivityDurationTrack(false);
		mProgress =(ProgressBar)context.findViewById(R.id.question_reply_progress);
	
		

		TextView mTitle = (TextView) context.findViewById(R.id.header).findViewById(R.id.header_title);
		String title =context.getString(R.string.question_reply_add_title);
		mTitle.setText(title);
		
		replyEt =(EditText)context.findViewById(R.id.question_reply_add_edit);
		
		LinearLayout  view =(LinearLayout)context.findViewById(R.id.question_reply_add_edit_layout);
		view.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				//replyEt.requestFocus();
			}
		});
		
		//返回主页按钮-------------------------------------------------------//
		 Button bBack = (Button) context.findViewById(R.id.header_bBack);
			
		 bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
					
					Home vHome = new Home();
					
					if (getActivity() instanceof MainActivity)
					{
						MainActivity activity = (MainActivity) getActivity();
						
						activity.switchContent(vHome);
					}
					
				}
			});
			
		//------------------------------------------------------------------//
		 
		 
		 Button reply_bt =(Button)context.findViewById(R.id.question_add_new_bt);
		 reply_bt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				reply =replyEt.getText().toString().trim();
				Log.i("SIMMON","reply= "+reply);
				if(reply==null||reply.equals("")){
					openDialog(NOT_RECORD);
				}else{
					mProgress.setVisibility(View.VISIBLE);
					ConnService();
				}
			}
		});
		 
		  
	}


		private void  ConnService(){
			
			//读取接口数据
			new Thread(){
				@Override
				public void run(){
				//你要执行的方法
					try {
						InitThisView();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				//执行完毕后给handler发送一个空消息
				handler.sendEmptyMessage(0);
				}
				}.start();
		}
		
		private void  InitThisView() throws IOException
		{
			//http://www.552120.com:8092/Question_Reply.aspx?QID=
			//45b6eb99-9e40-4d7b-bd89-38a803b5a59e&ownerID=1&isDr=1&reply=这里是医生的回复信息
			 String urlAPI = "http://www.552120.com:8092/Question_Reply.aspx?";
			 HttpPost httpRequest= new HttpPost(urlAPI);
			 List <NameValuePair> params = new ArrayList <NameValuePair>(); 
			 Log.d("SIMMON"," InitThisView QID= "+QID);
			 String id ="45b6eb99-9e40-4d7b-bd89-38a803b5a59e";
			 params.add(new BasicNameValuePair("QID",QID));

			// params.add(new BasicNameValuePair("QID",id));
			 String userID = String.valueOf(user.getUserId());
			 params.add(new BasicNameValuePair("ownerID",userID));
			 params.add(new BasicNameValuePair("isDr","0"));
			 params.add(new BasicNameValuePair("reply",reply));
			 Log.d("SIMMON"," InitThisView userID= "+userID);
			 Log.d("SIMMON"," InitThisView reply= "+reply);
			 try
			 {
				 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
				 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);		 
				 if(httpResponse.getStatusLine().getStatusCode() == 200)
				 {	
					 Log.d("SIMMON"," InitThisView  ");
					 JSONResult = EntityUtils.toString(httpResponse.getEntity()); 
					 Log.d("SIMMON"," InitThisView  JSONResult="+JSONResult);
				 }		 
			 }
			 catch(Exception e)
			 {		
				 Log.e("error:",  e.toString());
			 }

		}
		
		
		
		//定义Handler对象
		private Handler handler =new Handler(){
			@Override
			public void handleMessage(Message msg){
			super.handleMessage(msg);
			//处理UI
			if(JSONResult ==null){
				openDialog(NET_ERROR);
			}else{
				BindList(JSONResult);
				JSONResult =null;
			}
			}
		};
		

		
		//将JSON数据绑定到LISTVIEW
		private void BindList(String strJSON)
		{
			    try
			    {
			    	JSONObject jsonObject = new JSONObject(strJSON);
		            String result_str = jsonObject.getString("result");
		            Log.d("SIMMON"," result_str="+result_str);
		            int result = Integer.valueOf(result_str);
		            Log.d("SIMMON"," result="+result);
		            openDialog(result);
			    }
			    catch(JSONException ex)
			    {
			    		Log.e("JSON Error: ", ex.toString()); 
			    }
		}
		
		private  void updateViewData(List<QuestionReplyDate> datas ){		
			 Log.d("SIMMON"," BindList333  ");
			 mProgress.setVisibility(View.GONE);
			Adapter_QuestionReply adapter = new Adapter_QuestionReply(context, datas);
	        listView.setAdapter(adapter);
		}
	    
		  private void openDialog(final int result){
			   mProgress.setVisibility(View.GONE);
		        AlertDialog.Builder builder = new AlertDialog.Builder(context); 
		        builder.setIcon(null);
		        String login_result = context.getString(R.string.question_reply_add_fail);
		    
		        switch (result) {
		        case NET_ERROR:
		            login_result = getString(R.string.net_connet_fail);
		            break;
		        case NOT_RECORD:
		            login_result = getString(R.string.question_reply_add_noerror);
		            break;
		        case NOUSER_ERROR:
		            login_result = getString(R.string.cons_submit_nouser);
		            break;
		        case 1:
		        	login_result = getString(R.string.question_reply_add_sucess);
		        	break;
		        default:
		        	login_result = getString(R.string.question_reply_add_fail);
		         break;
		      }
		         TextView textview = new TextView(context);
		         textview.setText(login_result);
		         textview.setTextColor(Color.BLACK);
		         textview.setTextSize(18);

		         textview.setGravity(Gravity.CENTER);
		         builder.setView(textview);
		         
		         
		         builder.setPositiveButton("确定", new AlertDialog.OnClickListener() {
		             @Override
		             public void onClick(DialogInterface arg0, int arg1) {
		                 // TODO Auto-generated method stub
		                         context.switchContentHome();
		             }
		             
		         });
		         builder.create().show();
		         
		     }

}
